#!/bin/bash
set -x
ENGINE=${1:-vllm}
export USE_OPTIMIZED_MODEL=0
export VLLM_USE_V1=1
export HYDRA_FULL_ERROR=1

source /usr/local/Ascend/ascend-toolkit/set_env.sh
source /usr/local/Ascend/nnal/atb/set_env.sh

export SWANLAB_API_KEY="L9bkWEnSIVOGBTG8KTAhQ"
export SWANLAB_MODE="api"


PROJECT_NAME="test_agent_loop"

LOG_DIR="./logs/${PROJECT_NAME}"
export NCCL_DEBUG=WARNING
export VERL_LOGGING_LEVEL=WARNING
# --- Path Settings ---

SAVE_CHECKPOINT_DIR=/home/ma-user/work/checkpoints/test

REF_MODEL_PATH=/home/ma-user/work/models/Qwen2.5-VL-7B-Instruct

# --- Node and GPU Configuration ---
NNODES=1
N_GPUS_PER_NODE=16
WORLD_SIZE=$(($NNODES * $N_GPUS_PER_NODE))
EXPERIMENT_NAME="revpt_dataset_bs64_fixed_prompt_3B_stage1"+$(date +%Y%m%d_%H%M%S)

mkdir -p ${LOG_DIR}
mkdir -p tensorboard_dir/${PROJECT_NAME}
output_dir=/data/home/zdhs0094/data-from-5h100/verl/train_output/${PROJECT_NAME}/${EXPERIMENT_NAME}
output_image_dir=/data/home/zdhs0094/data-from-5h100/verl/train_output/${PROJECT_NAME}/${EXPERIMENT_NAME}/images
mkdir -p ${output_dir}
mkdir -p ${output_image_dir}
#



DATASET_EXPERT=/home/ma-user/work/datasets/REVPT-data/train0_deepeye_form.parquet
DATASET_EXPERT_REASONING=/home/ma-user/work/datasets/DeepEyes-Datasets-47k/options/chart_option_final.parquet

DATASET_VAL=/home/ma-user/work/datasets/REVPT-data/test_deepeye_form.parquet

PYTHONUNBUFFERED=1 python3 -m recipe.expert_rstar.rstar_main_grpo \
    --config-path='/data/home/zdhs0094/data-from-5h100/verl/recipe/expert_rstar/configs' \
    --config-name='expert_multiturn_grpo' \
    data.train_files=[${DATASET_EXPERT},${DATASET_EXPERT_REASONING}] \
    data.val_files=[${DATASET_VAL}] \
    data.train_batch_size=128 \
    data.val_batch_size=256 \
    trainer.seed=42 \
    data.dataloader_num_workers=16 \
    data.max_prompt_length=8192 \
    data.max_response_length=16384 \
    data.return_raw_chat=True \
    actor_rollout_ref.actor.use_dynamic_bsz=True\
    actor_rollout_ref.ref.log_prob_use_dynamic_bsz=True \
    data.filter_overlong_prompts=False \
    algorithm.adv_estimator=grpo \
    algorithm.kl_ctrl.kl_coef=0.0 \
    actor_rollout_ref.rollout.agent.num_workers=16 \
    actor_rollout_ref.model.path=${REF_MODEL_PATH} \
    actor_rollout_ref.model.use_remove_padding=True \
    actor_rollout_ref.model.use_fused_kernels=True \
    actor_rollout_ref.actor.optim.lr=1e-6 \
    actor_rollout_ref.actor.optim.lr_warmup_steps=20 \
    actor_rollout_ref.actor.ppo_mini_batch_size=64 \
    actor_rollout_ref.actor.ppo_max_token_len_per_gpu=32768 \
    actor_rollout_ref.actor.ppo_micro_batch_size_per_gpu=2 \
    actor_rollout_ref.actor.use_kl_loss=False \
    actor_rollout_ref.actor.kl_loss_coef=0.0 \
    actor_rollout_ref.actor.kl_loss_type=low_var_kl \
    actor_rollout_ref.actor.entropy_coeff=0.0 \
    actor_rollout_ref.actor.clip_ratio_low=0.2 \
    actor_rollout_ref.actor.clip_ratio_high=0.28 \
    actor_rollout_ref.actor.checkpoint.save_contents=['model','hf_model','optimizer','extra'] \
    actor_rollout_ref.actor.ulysses_sequence_parallel_size=1 \
    actor_rollout_ref.rollout.log_prob_micro_batch_size_per_gpu=1 \
    actor_rollout_ref.rollout.tensor_model_parallel_size=2 \
    actor_rollout_ref.rollout.name=$ENGINE \
    actor_rollout_ref.rollout.mode=async \
    actor_rollout_ref.rollout.n=32 \
    actor_rollout_ref.rollout.max_num_batched_tokens=32768 \
    actor_rollout_ref.rollout.gpu_memory_utilization=0.7 \
    actor_rollout_ref.rollout.enforce_eager=True \
    actor_rollout_ref.rollout.free_cache_engine=True \
    actor_rollout_ref.rollout.enable_chunked_prefill=True \
    actor_rollout_ref.actor.use_torch_compile=False \
    actor_rollout_ref.model.enable_gradient_checkpointing=True \
    actor_rollout_ref.actor.fsdp_config.param_offload=true \
    actor_rollout_ref.actor.fsdp_config.optimizer_offload=true \
    actor_rollout_ref.ref.log_prob_micro_batch_size_per_gpu=1 \
    actor_rollout_ref.ref.fsdp_config.param_offload=True \
    actor_rollout_ref.rollout.multi_turn.enable=True \
    actor_rollout_ref.rollout.multi_turn.max_assistant_turns=5 \
    actor_rollout_ref.rollout.multi_turn.max_user_turns=5 \
    actor_rollout_ref.rollout.multi_turn.max_parallel_calls=1 \
    actor_rollout_ref.rollout.multi_turn.max_tool_response_length=8192 \
    actor_rollout_ref.rollout.engine_kwargs.vllm.disable_mm_preprocessor_cache=True \
    actor_rollout_ref.rollout.multi_turn.tool_config_path=/data/home/zdhs0094/data-from-5h100/verl/recipe/expert/configs/expert_config.yaml \
    augmentation.do_down_sampling=True \
    augmentation.down_sampling_config.reject_equal_reward=True \
    augmentation.down_sampling_config.roc_error_ratio=True \
    augmentation.down_sampling_config.roc_answer_format=True \
    augmentation.down_sampling_config.min_zero_reward_trace_num=2 \
    augmentation.down_sampling_config.min_non_zero_reward_trace_num=2 \
    augmentation.down_sampling_config.down_sample_to_n=16 \
    trainer.critic_warmup=0 \
    trainer.logger=['console','tensorboard'] \
    trainer.val_before_train=False \
    trainer.n_gpus_per_node=${N_GPUS_PER_NODE} \
    trainer.nnodes=1 \
    trainer.save_freq=10 \
    trainer.test_freq=10 \
    trainer.device=npu "$@" \
    trainer.output_image_dir=${output_image_dir}\
    trainer.rollout_data_dir=${output_dir} \
    trainer.validation_data_dir=${output_dir}/valid \
    trainer.project_name=${PROJECT_NAME} \
    trainer.device=npu "$@" \
    trainer.experiment_name=${EXPERIMENT_NAME} \
    trainer.default_local_dir=${SAVE_CHECKPOINT_DIR}/${PROJECT_NAME}/${EXPERIMENT_NAME} \
    +trainer.tensorboard_dir=${SAVE_CHECKPOINT_DIR}/logs/tensorboard \
    +trainer.rl_logging_board_dir=${SAVE_CHECKPOINT_DIR}/logs/rl_logging_board \
    trainer.total_epochs=2 2>&1 | tee ${LOG_DIR}/${EXPERIMENT_NAME}.log